import { set } from 'mobx';
import { getItemForPk } from '../../config/product';
import { setSubscribe } from '../../services/gizwitsSdk';

import deviceDataModel from '../deviceData';

class Queue {
  constructor() {
    setInterval(() => {
      // 1秒检查一次
      this.pop();
    }, 1000);
  }

  static POP_NUM = 20;


  lock = false;

  queue = [];

  push = (item, callback) => {
    /**
     * 如果有重复的，就不加入队列
     */
    const matchDevice = this.queue.find(itemData => itemData.device.mac === item.mac);
    if (matchDevice) {
      return;
    }
    const productItem = getItemForPk(item.productKey);
    if ((productItem && !item.isSubscribed) || item.force) {
      const obj = {
        device: item,
        productSecret: item.productSecret,
        subscribed: true,
        callback,
      };
      this.queue.push(obj);
    }
  }

  pop = async () => {
    if (this.lock) {
      return;
    }
    this.lock = true;
    const list = [];
    for (let i = 0; i < Queue.POP_NUM; i++) {
      list.push(this.queue.pop());
    }
    this.consumption(list);
    this.lock = false;
  }

  consumption = async (list) => {
    // const promises = [];
    list.map(async (item) => {
      if (item) {
        const data = await setSubscribe(item);
        if (!deviceDataModel.data[item.device.did]) {
          deviceDataModel.initDeviceData(item.device);
        }
        item.callback(item.device, data);
      }
    });
  }
}

export default new Queue();
